<template>
  <div class="bar-root" :style="`height: ${height};`" :id="domId"></div>
</template>

<script>
import echarts from "echarts";
import {deepMerge} from '@/utils/assist.js'
import { setting } from './setting.js'

export default {
  name: "echarts-bar",
  components: {},
  props: {
    domId: {
      type: String,
      default: "echarts-bar",
    },
    height: {
      type: String,
      default: '300px'
    },
    chartsData: {
      type: Object,
      default: function() {
        return {
          xData: [],
          yData: [],  // [{name: '', data: []},{name: '', data: []}]
          // 如果只有一个柱子，则直接传数组 [1,2,3]
        }
      }
    },
    myOption: {
      type: Object,
      default: function() {
        return {}
      }
    },
  },
  data() {
    return {};
  },
  watch:{
    chartsData: {
      handler(newVal, oldVal) {
        // console.log(newVal)
        this.$nextTick(()=>{
          this.draw();
        })
        // this.draw();
      },
      deep: true,
      immediate: true,
    },
    myOption: {
      handler(newVal, oldVal) {
        // console.log(newVal)
        this.$nextTick(() => {
          this.draw();
        });
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    draw(){
      // console.log(document.getElementById(this.domId))

      if(!document.getElementById(this.domId)){
        console.warn('初始化echarts dom标签未找到')
        return
      }
      let myChart = echarts.init(document.getElementById(this.domId))
      let option = {
        tooltip: {},
        legend: {
          bottom: "0%"
        },
        xAxis: {
          data: this.chartsData.xData,
        },
        yAxis: {
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        series: [{
          name: "",
          type: "bar",
        }],
        color: setting.bar_colorList,
      }

      let yData = this.chartsData.yData
      if(yData[0]&&yData[0].data){
        option.series = []
        yData.forEach((item,index)=>{
          option.series.push({
            name: item.name,
            type: "bar",
            data: item.data,
          })
        })
      }else{
        option.series[0] = {
          name: '',
          type: "bar",
          data: yData
        }
      }

      option = deepMerge(option, this.myOption)
      // console.log(option)
      option && myChart.setOption(option)
      const that = this
      myChart.on('click',function(params){
        that.$emit('clickFuc',params)
      })
    }
  },
  mounted(){
    // console.log(document.getElementById(this.domId))
  },
};
</script>

<style lang="scss" scoped>
.bar-root {
  // height: 300px;
}
</style>
